#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # Matches stuff that should just be passed through as straight text.
  class TextSyntax < InlineSyntax
    getter substitute : String

    # Create a new `TextSyntax` which matches text on *pattern*.
    #
    # If *sub* is passed, it is used as a simple replacement for
    # *pattern*. If *start_character* is passed, it is used as a
    # pre-matching check which is faster than matching against
    # *pattern*.
    def initialize(pattern : String, sub : String = "", start_character : Int32? = nil, case_sensitive : Bool = true)
      @substitute = sub
      super(pattern, start_character: start_character, case_sensitive: case_sensitive)
    end

    # Adds a `Text` node to *parser* and returns `true` if there is a
    # `substitute`, as long as the preceding character (if any) is not
    # a `/`.
    #
    # Otherwise, the parser is advanced by the size of *match* and
    # `false` is returned.
    def on_match(parser : InlineParser, match : Regex::MatchData) : Bool
      match_begin = match.begin || 0
      if substitute.empty? || (match_begin > 0 && match.string[match_begin - 1...match_begin] == "/")
        # Just use the original matched text.
        parser.advance(match[0].size)
        return false
      end

      # Insert the substitution.
      parser.add_node(Text.new(@substitute))
      true
    end
  end
end
